/*
 * @Descripttion:
 * @Author: 446705260@qq.com
 * @Date: 2020-10-26 16:00:38
 * @LastEditors: 446705260@qq.com
 * @LastEditTime: 2020-10-27 13:50:13
 */
var axios = require("axios");
var moment = require("moment");
var exec = require("child_process").exec;
const opn = require("opn");
const os = require("os");

var cmdStr = `osascript -e 'display notification "程序已启动" with title "程序开始" sound name "Blow"'`;
var bingo = `osascript -e 'display notification "开抢开抢" with title "开抢开抢" sound name "Blow"'`;

const notify = (cmdStr) => {
  if (os.platform() == "darwin") {
    exec(cmdStr);
  }
};

const availability =
  "https://reserve-prime.apple.com/CN/zh_CN/reserve/A/availability.json";

console.log("在打开的浏览器里面先登录吧，免得预约之后再登录会慢一拍");
opn("https://www.apple.com.cn");
notify(cmdStr);

const cityId = "R670";
const model = "MGLD3CH/A";
const color = "海蓝色";
const capacity = "128GB";
const time = 3; //查询间隔3秒一次
const quantity = 1;
const bookUrl = `https://reserve-prime.apple.com/CN/zh_CN/reserve/A?color=${color}&capacity=${capacity}&quantity=${quantity}&anchor-store=${cityId}&store=${cityId}&partNumber=${model}&channel=&sourceID=&iUID=&iuToken=&iUP=N&appleCare=&rv=&path=&plan=unlocked`;

setInterval(() => {
  axios
    .get(availability)
    .then((response) => {
      console.log("response", response.data);
      if (response.data.stores) {
        const a = response.data.stores[cityId][model].availability;
        console.log(
          "检测中,官方最后一次更新时间：" +
            moment(response.data.updated).format("YYYY-MM-DD HH:mm:ss") +
            "___当前时间" +
            moment().format("YYYY-MM-DD HH:mm:ss"),
          a.contract || a.unlocked
            ? "有货！！！！！！！！！！！！！！！！！！！！！！"
            : "无货"
        );
        if (a.contract || a.unlocked) {
          notify(bingo);
          opn(bookUrl);
        }
      } else {
        console.log(
          "官方未返回库存信息" +
            "___当前时间" +
            moment().format("YYYY-MM-DD HH:mm:ss")
        );
      }
    })
    .catch((error) => {
      console.log(error); //捕获错误
    });
}, time * 1000);
